package com.skyvin.nreceipts.common.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.skyvin.nreceipts.common.document.AppUser;
import com.skyvin.nreceipts.common.exception.NReceiptsRunTimeException;
import com.skyvin.nreceipts.common.value.ErrorValue;
import com.skyvin.nreceipts.user.service.UserService;

public class BaseController {
	private Logger logger = Logger.getLogger(BaseController.class);
	
	@Autowired 
	UserService userService;

	@ExceptionHandler
	@ResponseBody
	 public ErrorValue handleRuntimeException(RuntimeException r, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		ErrorValue errorValue = new ErrorValue(r.getMessage(), r.toString());
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		//modelMap.put("stacktrace", r.getStackTrace());
		logger.error("RuntimeException: " + r.toString());
		r.printStackTrace();
        return errorValue;
    }
	
	@ExceptionHandler
	@ResponseBody
	 public ErrorValue handleRuntimeException(IOException ioException, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		ErrorValue errorValue = new ErrorValue(ioException.getMessage(), ioException.toString());
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		//modelMap.put("stacktrace", r.getStackTrace());
		logger.error("RuntimeExcpetion: " + ioException.toString());
		ioException.printStackTrace();
        return errorValue;
    }
	
	@ExceptionHandler
	@ResponseBody
	 public ErrorValue handleRuntimeException(NReceiptsRunTimeException nReceiptsRunTimeException, HttpServletResponse response) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		ErrorValue errorValue = new ErrorValue(nReceiptsRunTimeException.getMessage(), nReceiptsRunTimeException.toString());
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		//modelMap.put("stacktrace", r.getStackTrace());
		logger.error("RuntimeExcpetion: " + nReceiptsRunTimeException.toString());
        return errorValue;
    }
	
	public String getCurrentUserPID() {
		return userService.getCurrentUserPID();
	}
	
	public AppUser getCurrentAppUser() {
		return userService.getCurrentAppUser();
	}

}
